<?php

// @formatter:off
/**
 * @file collections.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: collections.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/frontview/actions/content/collections.php $
 */
// @formatter:on

class ActionControllerContentCollections extends WCActionController {
	//
	// Public methods.
	public function check() {
		$check = parent::check();

		if($check == WC_HTTPERROR_OK) {
			global $wcProfile;

			if(!$wcProfile->allowedTo(WC_PERM_COLLECTION_LIST)) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_FORBIDDEN;
				$errno = $check;
				$error = "You're not allowed to list collections";
			}
		}

		return $check;
	}
	//
	// Protected methods.
	protected function subRun() {
		$ok = true;

		//
		// Loading global pointers.
		global $wcSkinConfig;
		global $wcGroup;
		global $wcProfile;

		if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["ACTION"])) {
			switch($_POST["ACTION"]) {
				case "REMOVE":
					if($wcProfile->allowedTo(WC_PERM_COLLECTION_EDIT)) {
						if(isset($_POST["ID"])) {
							$collection = WCCollectionsHolder::I()->item($_POST["ID"]);
							if($collection) {
								$collection->remove();
							}
						}
					}
					break;
			}
		}

		$page = isset($_REQUEST["page"]) ? $_REQUEST["page"] : 1;
		$minCollectionInPage = $wcSkinConfig->max_per_page->collections * ($page - 1);
		$maxCollectionInPage = $minCollectionInPage + $wcSkinConfig->max_per_page->collections;

		$this->_manager->PATH = "Top Collections (page {$page})";

		//
		// Selecting only top collections in range.
		$collections = array();
		$items = WCCollectionsHolder::I()->topItems($wcGroup);
		$collectionCount = 0;
		uasort($items, "WCCollection::NameSort");
		foreach($items as $collection) {
			if($collection->ok()) {
				if($collectionCount >= $minCollectionInPage && $collectionCount < $maxCollectionInPage) {
					$collections[] = $collection;
				}
				$collectionCount++;
			}
		}

		WCFVPager::GetAssignsIntoManager(ceil($collectionCount / $wcSkinConfig->max_per_page->collections));

		//
		// Creating multi-array by prefix
		$lists = array();
		$ids = 1;
		foreach($collections as $collection) {
			$name = $collection->name;
			$prefix = strtoupper(isset($name[0]) ? $name[0] : "#");
			if($prefix < 'A' || $prefix > 'Z') {
				$prefix = '#';
			}
			$prefix = "{$prefix}";
			if(!isset($lists[$prefix])) {
				$lists[$prefix] = array(
					"prefix" => $prefix,
					"list" => array()
				);
			}

			$lists[$prefix]["list"][] = WCFVBoxes::GetCollectionPreviewAssigns($collection);
		}
		ksort($lists);

		$this->_manager->collections_lists = $lists;

		if($wcProfile->allowedTo(WC_PERM_COLLECTION_ADD)) {
			$this->_manager->collections_create = true;
		}

		return $ok;
	}
}
